package kb_sys

import (
	"context"
	"fmt"
	mCache "service/model/hr_cache"
	model "service/model/kb_sys"
	"service/model/mod"

	gupb "gitee.com/cloudapex/protos/hr_cache/pb"
	gpb "gitee.com/cloudapex/protos/sys_know/pb"
	"gitee.com/cloudapex/ulern/htp"
	"gitee.com/cloudapex/ulern/util"
	"github.com/gin-gonic/gin"
)

/**
职能对接人员列表
*/
type FuncList struct {
	Title   string `form:"title" json:"title"`
	Desc    string `form:"desc" json:"desc"`
	Creator string `form:"creator" json:"creator"`
	Page    int64  `form:"page" json:"page"`
	Count   int64  `form:"pnum" json:"count"`
	Type    int64  `form:"type" json:"type"` //类型 1：职能对接人员,2:员工手册
	Order   int64  `form:"order" json:"order" binding:"omitempty"`
	Orule   int    `form:"orule" json:"orule" binding:"omitempty"`
	StartId int64  `form:"start_id" json:"start_id" binding:"omitempty"`
	State   int64  `form:"state" json:"state"` //状态： 1 草稿, 2 发布，3 停用， 4 删除
}

type ResList struct {
	UserName string `json:"userName"`
	Id       int64  `json:"id"`      //自增id
	CId      int64  `json:"cId"`     //公司ID
	Title    string `json:"title"`   //标题
	UId      int64  `json:"uId"`     //操作用户ID
	Content  string `json:"content"` //内容（ 富文本编辑内容 ）
	State    int64  `json:"state"`   //状态： 1 草稿, 2 发布，3 停用， 4 删除
	At       int64  `json:"at"`      //数据入库时间
	FileUrl  string `json:"fileUrl"` //附件 多个，分割 (员工手册需要)
	Status   int64  `json:"status"`  //状态值 1 数据库错误 2 无数据 3 数据已存在 4 参数错误 （暂定）
	Message  string `json:"message"` //状态说明
}

type NameInfo struct {
	Id   int64  `json:"id"`
	Name string `json:"name"`
}

func (this *FuncList) Handle(c *gin.Context, ctx context.Context) htp.Response {

	jwtUser := mod.CurrUser(c)
	knReq := &gpb.SysKnowReq{}
	knReq.Title = this.Title
	knReq.CId = jwtUser.CId
	knReq.State = this.State

	sysreq := gpb.SysKnowListReq{
		Count:      this.Count,
		Type:       this.Type,
		Page:       this.Page,
		SysKnowReq: knReq,
		StartId:    this.StartId,
	}

	if this.Order == 0 {
		this.Order = 1
	}
	sysreq.DesClum = this.Order

	sysreq.IsDes = 2
	if this.Orule == 0 {
		sysreq.IsDes = 1
	}

	list, err := model.Sys.GetList(ctx, &sysreq)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if list.Status != 0 && list.Status != 2 {

		return htp.RespErr(int(list.Status), list.Message, nil)
	}

	lis := make([]ResList, 0)
	var nameList []NameInfo
	nameList = make([]NameInfo, 0)

	for _, v := range list.SysList {
		var res string
		res, err, nameList = GetInfoNew(ctx, v.UId, nameList)
		if err != nil {
			return htp.RespModelErr("", err)
		}
		var info ResList
		if res != "" {
			info.UserName = res
		}
		util.Convert(&info, v)
		lis = append(lis, info)
	}

	return htp.RespOK("", &struct {
		Page  int64 `json:"page"`
		Total int64 `json:"total"`
		List  []ResList
	}{Page: list.Page, Total: list.Count, List: lis})
}

func GetInfoNew(ctx context.Context, id int64, list []NameInfo) (string, error, []NameInfo) {

	for _, v := range list {
		if v.Id == id {
			return v.Name, nil, list
		}
	}

	idList := make([]int64, 0)
	idList = append(idList, id)
	req := &gupb.UserLoginReqIdsReq{
		Ids: idList,
	}
	res, err := mCache.UserCacheServer.UserNameList(ctx, req)

	if err != nil {
		return "", err, nil
	}

	if len(res.NameList) == 0 {
		return "", nil, list
	}

	var info NameInfo
	info.Id = id
	info.Name = res.NameList[0].Name
	list = append(list, info)
	return res.NameList[0].Name, nil, list

}

/**
职能对接人员详情
*/
type Info struct {
	Id   int64 `form:"id" json:"id" binding:"required"`
	Type int64 `form:"type" json:"type" binding:"required"`
}

type InfoRes struct {
	Id       int64  `json:"id"`      //自增id
	CId      int64  `json:"cId"`     //公司ID
	Title    string `json:"title"`   //标题
	UId      int64  `json:"uId"`     //操作用户ID
	Content  string `json:"content"` //内容（ 富文本编辑内容 ）
	State    int64  `json:"state"`   //状态： 1 草稿, 2 发布，3 停用， 4 删除
	At       int64  `json:"at"`      //数据入库时间
	FileUrl  string `json:"fileUrl"` //附件 多个，分割 (员工手册需要)
	Status   int64  `json:"status"`  //状态值 1 数据库错误 2 无数据 3 数据已存在 4 参数错误 （暂定）
	Message  string `json:"message"` //状态说明
	UserName string `json:"user_name"`
}

func (this *Info) Handle(c *gin.Context, ctx context.Context) htp.Response {

	jwtUser := mod.CurrUser(c)
	req := &gpb.SysKnowReq{
		Id:   this.Id,
		Type: this.Type,
		CId:  jwtUser.CId,
	}
	res, err := model.Sys.Info(ctx, req)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if res.Status != 0 {
		return htp.RespErr(int(res.Status), res.Message, nil)
	}

	nameList := make([]NameInfo, 0)
	var name string
	name, err, nameList = GetInfoNew(ctx, res.UId, nameList)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	var res1 InfoRes
	util.Convert(&res1, res)
	res1.UserName = name
	return htp.RespOK("", res1)
}

/**
添加职能对接人员
*/
type AddFunc struct {
	Title   string `form:"title" json:"title" binding:"required"`
	Desc    string `form:"desc" json:"desc" binding:"required"`
	Type    int64  `form:"type" json:"type" binding:"required"`
	FileUrl string `form:"file_url" json:"file_url" binding:"omitempty"`
}

func (this *AddFunc) Handle(c *gin.Context, ctx context.Context) htp.Response {

	jwtUser := mod.CurrUser(c)
	req := &gpb.SysKnowReq{
		Type:    this.Type,
		CId:     jwtUser.CId,
		UId:     jwtUser.UId,
		Title:   this.Title,
		State:   1,
		Content: this.Desc,
		FileUrl: this.FileUrl,
	}
	res, err := model.Sys.Add(ctx, req)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if res.Status != 0 {
		return htp.RespErr(int(res.Status), res.Message, nil)
	}

	return htp.RespOK("", "")
}

type EditFunc struct {
	Id      int64  `form:"id" json:"id" binding:"required"`
	Title   string `form:"title" json:"title"`
	Desc    string `form:"desc" json:"desc"`
	Type    int64  `form:"type" json:"type" binding:"required"`
	FileUrl string `form:"file_url" json:"file_url" binding:"omitempty"`
}

func (this *EditFunc) Handle(c *gin.Context, ctx context.Context) htp.Response {

	jwtUser := mod.CurrUser(c)
	req := &gpb.SysKnowReq{
		Type: this.Type,
		CId:  jwtUser.CId,
		//State: 1,
		Id:      this.Id,
		FileUrl: this.FileUrl,
	}

	if this.Title != "" {
		req.Title = this.Title
	}
	if this.Desc != "" {
		req.Content = this.Desc
	}
	res, err := model.Sys.Edit(ctx, req)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if res.Status != 0 {
		return htp.RespErr(int(res.Status), res.Message, nil)
	}
	return htp.RespOK("", "")
}

type SetStatus struct {
	Id     int64 `form:"id" json:"id" binding:"required"`
	Status int64 `form:"status" json:"status" binding:"required"`
	Type   int64 `form:"type" json:"type" binding:"required"`
}

func (this *SetStatus) Handle(c *gin.Context, ctx context.Context) htp.Response {

	jwtUser := mod.CurrUser(c)
	req := &gpb.SysKnowReq{
		Id:    this.Id,
		State: this.Status,
		CId:   jwtUser.CId,
		Type:  this.Type,
	}

	fmt.Println(this.Status)
	fmt.Println(req)

	res, err := model.Sys.Edit(ctx, req)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if res.Status != 0 {
		return htp.RespErr(int(res.Status), res.Message, nil)
	}
	return htp.RespOK("", "")
}
